import time
import asyncio
from playwrightView import MeishitianxiaPlaywright
from until import time_print
from setting import DEBUG_PRINT, PARAM
from taskLog import AsyncTaskLogger

async def monitor_loop():
    """监控 event loop 状态"""
    start_time = time.time()
    while True:
        await asyncio.sleep(10)  # 每10秒打印一次状态
        current_time = time.time()
        running_time = current_time - start_time
        task_count = len(asyncio.all_tasks())
        time_print(f"=== Event Loop 监控 ===")
        time_print(f"运行时间: {running_time:.1f}秒")
        time_print(f"当前任务数: {task_count}")
        time_print(f"=======================")

async def main():

    param = PARAM

    monitor_task = asyncio.create_task(monitor_loop())

    try:
        caipu = MeishitianxiaPlaywright(param)
        await caipu.init_playwright()
        await caipu.processCategory()
    finally:
        # 取消监控任务
        monitor_task.cancel()
        try:
            await monitor_task
        except asyncio.CancelledError:
            pass
        
        # 清理logger资源
        AsyncTaskLogger.cleanup_all_loggers()
        time_print("已清理所有logger资源")

if __name__ == "__main__":
    asyncio.run(main())

    #用法
    # step 1. 
    #   1.配置conda环境
    #   2.  playwright install-deps
    #       playwright install chromium
    # step 2 配置代理
    #   1.添加服务器白名单 curl checkip.amazonaws.com
    #   2.修改proxy.py里的self.ipAPI
    # step 3 配置redis
    #   1.安装redis
    #   2.拷贝CSV目录
    #   3.运行python csvToRedis.py csv ./CSV
    # step 4 修改采集范围
    #   1.setting.py里修改采集范围categoryRange
    #   2.注销修改playwrightView.py里的--disable-gpu
    #   3.修改headless=True
